import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import {
  getCrifAreaList,
  searchByCompany,
  getRecerdsList,
  getPrice,
  saveOutbuyerInfo,

  updateOrder,
  getOrderById,
  queryProductList,
  getBusinessParamsByCode,
  getAllCurrencys,
  getAllPorts,
  addRule,
  removeRule,
  updateRule,
} from './service';
import { TableListData } from './data.d';
import Constants from '../foreignTraderQuery/utils/Constants';
import {decrypt} from '../foreignTraderQuery/utils/commons';
const R = require('ramda');
const productAddTempIdPrefix = 'productAddTempIdPrefix_';
export interface StateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    add: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'foreignTraderQuery',

  state: {
    list: [],
    pagination: {},
    crifCountrys: [], //国外买家评估国家和地区
    crifRegions: [],  //国外买家评估州
    pageListData: [], //分页列表数据
    price: {}, //价格数据

    productList: [], //产品列表
    productPage: {}, //产品列表分页
    bizParams: {}, // 业务参数缓存
    currencys: [], // 币种列表
    ports: [], //报关口岸列表
    order: {}, //订单详情
    orderTgApproval: {}, //订单通关信息
    orderProductDetails: [], //订单产品

    recordList: [], //购买记录列表数据
    recordPage: {}, //购买记录列表分页
  },

  effects: {
    /**
     * 查询国外买家评估国家和地区
     *
     * @param call
     * @param put
     */
      *getCrifAreaList({ payload }, { call, put }) {
      const response = yield call(getCrifAreaList, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            crifCountrys: response.content.crifCountrys,
            crifRegions: response.content.crifRegions
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { crifCountrys: [], crifRegions: []} });
      }
    },

    *fetch({ payload }, { call, put }) {
      payload.lesseeCode = Constants.LESSEE_CODE;
      const response = yield call(searchByCompany, payload);
      if (response.resultCode === 'ok') {
        if (!R.isEmpty(response.content) && !R.isNil(response.content)) {
          let content = JSON.parse(decrypt(response.content, Constants.LESSEESHORTNAME));

          let pageListData = content.map(item => {
            let data = {};
            data.name = item.entity.name
            data.address = item.entity.addresses[0].address
            data.zipCode = item.entity.addresses[0].zipCode
            data.countryCode = item.entity.addresses[0].countryCode
            return data;
          });
          yield put({type: 'refreshState', payload: {list: content, pageListData: pageListData} });

        } else {
          yield put({type: 'refreshState', payload: {list: [], pageListData: []} });
        }
      }
    },

    *getRecerdsList({ payload }, { call, put }) {
      const response = yield call(getRecerdsList, payload);
      let page = response.content.page;

      if (response.resultCode === 'ok') {
          yield put({
            type: 'refreshState',
            payload: {
              recordList: response.content.list,
              recordPage: {current: 1, pageSize: page.size, total: page.totalRow}
            }
          });

        } else {
          yield put({
            type: 'refreshState',
            payload: {
              recordList: [],
              recordPage: {}
            }
          });

        }
    },

    /**
     * 查询报告价格
     *
     * @param call
     * @param put
     */
      *getPrice({ payload }, { call, put }) {
      const response = yield call(getPrice, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            price: response.content,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { price: {} } });
      }
    },

    /**
     * 保存买家信息
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *saveOutbuyerInfo({ payload }, { call, put, select }) {
      const response = yield call(saveOutbuyerInfo, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      if (response.resultCode === 'ok') {
        if (payload.onSuccess) payload.onSuccess(response.content);
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 更新订单
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *updateOrder({ payload }, { call, put, select }) {
      const dataSource = payload.dataSource;
      let orderProductDetails = [];
      R.map(
        product => {
          let temp = R.omit([
            'key',
            'createtime',
            'creator',
            'status',
            'updater',
            'updatetime',
            'productbranchname',
          ])(product);
          if (R.contains(productAddTempIdPrefix)(temp.id)) {
            temp.id = ''; //去掉新增临时定义的id
          }
          orderProductDetails = R.concat(orderProductDetails, [temp]);
        },
        R.isNil(dataSource.orderProductDetails) ? [] : dataSource.orderProductDetails,
      ); //去掉key
      dataSource.orderProductDetails = orderProductDetails;
      const response = yield call(updateOrder, { ...dataSource });
      if (response.resultCode === 'ok') {
        message.info('订单修改成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 根据id获取订单详情
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *getOrderById({ payload }, { call, put, select }) {
      const response = yield call(getOrderById, { id: payload.id });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            order: response.content.order,
            orderProductDetails: response.content.orderProductDetails,
            orderTgApproval: response.content.orderTgApproval,
          },
        });
      } else {
        message.error(response.errMessage);
      }
    },



    /**
     * 分页查询产品
     *
     * @param call
     * @param put
     * @param select
     */
    *queryProductList({ payload }, { call, put, select }) {
      const response = yield call(queryProductList, { ...payload });
      if (response.resultCode === 'ok') {
        let content = response.content;
        yield put({
          type: 'refreshState',
          payload: {
            productList: content.list,
            productPage: R.isNil(content.page) ? Constants.DEFAULT_PAGE : content.page,
          },
        });
      } else {
        message.error(response.errMessage);
      }
    },

    /**
     * 获取业务参数集合
     *
     * @param call
     * @param put
     * @param select
     */
    *getBusinessParamsByCode({ sprCode }, { call, put, select }) {
      const sessionSprCode = sessionStorage.getItem(Constants.PARAMPREFIX + sprCode);
      if (R.isNil(sessionSprCode)) {
        const response = yield call(getBusinessParamsByCode, { sprCode });
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PARAMPREFIX + sprCode, JSON.stringify(response.content));
          yield put({
            type: 'setBizParams',
            payload: {
              sprCode,
              list: response.content,
            },
          });
        }
      } else {
        yield put({ type: 'setBizParams', payload: { sprCode, list: JSON.parse(sessionSprCode) } });
      }
    },

    /**
     * 获取所有币种
     *
     * @param call
     * @param put
     */
    *getAllCurrencys({}, { call, put, select }) {
      const sessionCurrency = sessionStorage.getItem(Constants.preCurrency);
      if (R.isNil(sessionCurrency)) {
        const response = yield call(getAllCurrencys);
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.preCurrency, JSON.stringify(response.content));
          yield put({ type: 'refreshState', payload: { currencys: response.content } });
        }
      } else {
        yield put({ type: 'refreshState', payload: { currencys: JSON.parse(sessionCurrency) } });
      }
    },

    /**
     * 获取所有口岸
     *
     * @param call
     * @param put
     */
    *getAllPorts({}, { call, put, select }) {
      const sessionPort = sessionStorage.getItem(Constants.PORTS);
      if (R.isNil(sessionPort)) {
        const response = yield call(getAllPorts, { status: '1' });
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PORTS, JSON.stringify(response.content));
          yield put({ type: 'refreshState', payload: { ports: response.content } });
        }
      } else {
        yield put({ type: 'refreshState', payload: { ports: JSON.parse(sessionPort) } });
      }
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    /**
     * 设置业务参数
     *
     * @param state
     * @param payload
     */
    setBizParams(state, { payload }) {
      let newState = state.bizParams;
      if (payload.sprCode != undefined) {
        newState[payload.sprCode] = payload.list;
      }
      return { ...state, bizParams: newState };
    },

    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
